<template>
	<view class="">
		<!-- <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :multiple="multiple"
			:maxCount="disable ? fileList.length ||0 : maxCount"
			:uploadIcon="accept === 'file' ? 'file-text' : 'camera-fill'" :deletable="!disable" :accept="accept"
			:disabled="disable"></u-upload> -->
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :multiple="multiple"
			:maxCount="disable ? fileList.length ||0 : maxCount" uploadIcon="camera-fill" :deletable="!disable"
			:accept="'image'" :disabled="disable"></u-upload>
	</view>
</template>

<script>
	import {
		uploadFile,
		getFileList
	} from '@/common/api.js'
	import config from '@/common/config.js'
	export default {
		name: 'fileUpload',
		props: {
			maxCount: {
				type: Number,
				default: 10
			},
			accept: {
				type: String,
				default: 'image'
			},
			multiple: {
				type: Boolean,
				default: true
			},
			fileIds: {
				type: String,
				default: ''
			},
			disable: {
				type: Boolean,
				default: false
			},
			list: {
				type: Array,
				default: () => {
					return []
				}
			},
			bizType: {
				type: String,
				default: ''
			},
			bizId: {
				type: String,
				default: ''
			},

		},
		data() {
			return {
				fileList: [],
			}
		},
		watch: {
			fileIds: {
				handler: 'getFileList',
				immediate: true // 初始化时立即执行
			},
			list: {
				immediate: true, //立即执行
				deep: true,
				handler(newValue, oldValue) {
					// console.log(newValue, 'newValue1111');
					if (newValue && newValue.length) {
						this.fileList = newValue
						// console.log(this.fileList, 'newValue122');
					}
				},
			},
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.$emit('updataFile', this.fileList)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;

				// 先不直接添加到fileList，而是等待上传成功后再添加
				for (let i = 0; i < lists.length; i++) {
					try {
						// 处理文件名：name为空时，从url最后一节提取
						let fileName = lists[i].name;
						if (!fileName || fileName.trim() === '') {
							// 分割url，取最后一段作为文件名
							const urlSegments = lists[i].url.split('/');
							fileName = urlSegments[urlSegments.length - 1] || `file_${Date.now()}`;
						}
						uni.showLoading({
							title: '上传中',
							mask: true
						});
						const result = await this.uploadFileImage({
							name: 'file',
							filePath: lists[i].url,
							formData: {
								fileName: fileName, // 使用处理后的文件名
								name: fileName // 保持和fileName一致
							}
						});
						uni.hideLoading()

						// 只有上传成功才添加到fileList
						this.fileList.push({
							...lists[i],
							status: "success",
							message: "",
							url: config.baseFileUrl + result.id,
							fileId: result.id,
							name: fileName // 把处理后的文件名也存到fileList中，方便后续使用
						});
					} catch (error) {
						console.error('上传失败:', error);
						// 上传失败可选择添加失败状态（按需启用）
						/*
						this.fileList.push({
						  ...lists[i],
						  status: "failed",
						  message: "上传失败",
						  url: lists[i].url,
						  name: lists[i].name || lists[i].url.split('/').pop() || '未知文件'
						});
						*/
					}
				}

				this.$emit('updataFile', this.fileList)
			},
			async uploadFileImage(data) {
				return new Promise((resolve, reject) => {
					uploadFile(data).then(res => {
						resolve(res);
					}).catch(err => {
						reject(err);
					})
				})
			},
			async getFileList() {
				if (!this.fileIds) return

				if (this.bizId == '' && this.bizType == '') {
					this.fileList = this.fileIds.split(',').map(item => {
						return {
							url: config.baseFileUrl + item,
							fileId: item
						}
					})
				} else {
					let res = await getFileList({
						bizType: this.bizType,
						bizId: this.bizId
					})
					if (res.data) {
						this.fileList = res.data.map(item => {
							return {
								...item,
								url: config.baseFileUrl + item.fileId,
								name: item.fileName,
							}
						})
					}
				}
			}

		}
	}
</script>

<style>
</style>